
import axios from "axios";
import type { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from "axios";

// 创建axios实例，直接使用空的baseURL，让请求路径完全匹配mock配置
const request:AxiosInstance = axios.create({
  baseURL: '', // 不设置baseURL，直接使用相对路径
  timeout: 10000,
  headers: { 
    'Content-Type': 'application/json',
  },
});

// 手动添加API前缀
const addApiPrefix = (url: string): string => {
  // 如果URL已经以/api开头，或者是绝对路径，就不添加前缀
  if (url.startsWith('/api') || url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  // 否则添加/api前缀
  return `/api${url}`;
};

//请求拦截器
request.interceptors.request.use(
  (config:InternalAxiosRequestConfig) => {
    // 确保URL带有/api前缀
    config.url = addApiPrefix(config.url || '');


    const userInfo = localStorage.getItem('user');
    
    if (userInfo) {
      const user = JSON.parse(userInfo);
      if(user.token){
        config.headers = config.headers || {};

        (config.headers as any)['Authorization'] = `Bearer ${user.token}`; 
      }
    }
    return config;
  },
  (error) => {
    console.error('请求拦截器错误:', error);
    return Promise.reject(error);
  }
);



//响应拦截器
request.interceptors.response.use(
  (response:AxiosResponse) => {
    return response.data;
  },
  (error) => {
    console.error('响应拦截器错误,url:', error.response?.config?.url);
    console.error('响应拦截器错误,状态码:', error.response?.status);
    if (error.response?.status === 401) {
      window.location.href = '/login';
    } 
    return Promise.reject(error);
  }
);


// 默认导出请求实例，保持向后兼容性
export default request;